package org.bite.lesson11;

import java.util.concurrent.locks.ReentrantLock;

/**
 * 用ReentrantLock创建两个线程对一个变量进行累加
 */
public class Demo1104 {
    public static void main(String[] args) throws InterruptedException {
        Counter1104 counter = new Counter1104();
        Thread t1 = new Thread(()->{
            for(int i = 0; i < 5000; i++){
                counter.increase();
            }
        });

        Thread t2 = new Thread(()->{
            for(int i = 0; i < 5000; i++){
                counter.increase();
            }
        });

        t1.start();
        t2.start();

        t1.join();
        t2.join();
        System.out.println("count = " + counter.count);
    }
}
class Counter1104 {
    public volatile int count = 0;
    ReentrantLock lock = new ReentrantLock();
    public void increase() {
        try{
            lock.lock();
            count++;
        }finally{
            lock.unlock();
        }
    }
}
